package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.itheima.sfbx.file.feign.FileBusinessFeign;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.constant.category.CategoryConstant;
import com.itheima.sfbx.framework.commons.constant.insure.InsureConstant;
import com.itheima.sfbx.framework.commons.dto.basic.TreeItemVO;
import com.itheima.sfbx.framework.commons.dto.basic.TreeVO;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.utils.NoProcessing;
import com.itheima.sfbx.insurance.constant.CategoryCacheConstant;
import com.itheima.sfbx.insurance.dto.CategoryCoefficentVO;
import com.itheima.sfbx.insurance.dto.CategoryConditionVO;
import com.itheima.sfbx.insurance.dto.CategorySafeguardVO;
import com.itheima.sfbx.insurance.dto.CategoryVO;
import com.itheima.sfbx.insurance.enums.CategoryEnum;
import com.itheima.sfbx.insurance.mapper.CategoryMapper;
import com.itheima.sfbx.insurance.pojo.Category;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.CategoryCondition;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICategoryConditionService;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：保险分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    ICategoryConditionService categoryConditionService;

    @Autowired
    ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    ICategorySafeguardService categorySafeguardService;

    private LambdaQueryWrapper<Category> queryWrapper(CategoryVO vo){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(vo.getParentCategoryNo()),Category::getParentCategoryNo,vo.getParentCategoryNo());
        lqw.eq(StrUtil.isNotBlank(vo.getCategoryNo()),Category::getCategoryNo,vo.getCategoryNo());
        lqw.like(StrUtil.isNotBlank(vo.getCategoryName()),Category::getCategoryName,vo.getCategoryName());
        lqw.eq(StrUtil.isNotBlank(vo.getCategoryType()),Category::getCategoryType,vo.getCategoryType());
        lqw.eq(StrUtil.isNotBlank(vo.getDataState()),Category::getDataState,vo.getDataState());
        lqw.eq(StrUtil.isNotBlank(vo.getLeafNode()),Category::getLeafNode,vo.getLeafNode());
        lqw.eq(StrUtil.isNotBlank(vo.getShowIndex()),Category::getShowIndex,vo.getShowIndex());
        return lqw;
    }

    private void buildVoList(List<CategoryVO> voList){
        Set<String> noSet = voList.stream().map(CategoryVO::getCategoryNo).collect(Collectors.toSet());
        List<CategoryCondition> conditionList = categoryConditionService.lambdaQuery()
                .in(CategoryCondition::getCategoryNo, noSet)
                .list();
        Map<String, List<CategoryCondition>> conditionMap = conditionList.stream().collect(Collectors.groupingBy(CategoryCondition::getCategoryNo));
        List<CategoryCoefficent> coefficentList = categoryCoefficentService.lambdaQuery().in(CategoryCoefficent::getCategoryNo, noSet).list();
        Map<String, List<CategoryCoefficent>> coefficentMap = coefficentList.stream().collect(Collectors.groupingBy(CategoryCoefficent::getCategoryNo));
        List<CategorySafeguard> safeguardList = categorySafeguardService.lambdaQuery().in(CategorySafeguard::getCategoryNo, noSet).list();
        Map<String, List<CategorySafeguard>> safeguardMap = safeguardList.stream().collect(Collectors.groupingBy(CategorySafeguard::getCategoryNo));

        for (CategoryVO vo : voList) {
            List<CategoryCondition> conditions = conditionMap.get(vo.getCategoryNo());
            vo.setCategoryConditionVOs(BeanConv.toBeanList(conditions,CategoryConditionVO.class));
            List<CategoryCoefficent> coefficents = coefficentMap.get(vo.getCategoryNo());
            vo.setCategoryCoefficentVOs(BeanConv.toBeanList(coefficents, CategoryCoefficentVO.class));
            List<CategorySafeguard> safeguards = safeguardMap.get(vo.getCategoryNo());
            vo.setCategorySafeguardVOs(BeanConv.toBeanList(safeguards,CategorySafeguardVO.class));
        }

    }


    @Override
    public Page<CategoryVO> findPage(CategoryVO categoryVO, int pageNum, int pageSize) {
        //TODO
        LambdaQueryWrapper<Category> lqw = queryWrapper(categoryVO);
        Page<Category> page = this.page(new Page<>(pageNum, pageSize),lqw);
        Page<CategoryVO> voPage = BeanConv.toPage(page, CategoryVO.class);
        List<CategoryVO> voList = voPage.getRecords();
        if (CollUtil.isEmpty(voList)) {
            return voPage;
        }
        buildVoList(voList);
        return voPage;
    }

    @Override
    @Transactional
    public CategoryVO save(CategoryVO categoryVO) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public Boolean update(CategoryVO categoryVO) {
        //TODO
        Category bean = getById(categoryVO.getId());
        if(bean==null){
            throw new ProjectException(CategoryEnum.UPDATE_FAIL);
        }

        updateById(BeanConv.toBean(categoryVO,Category.class));
        categorySafeguardService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categoryCoefficentService.deleteByCategoryNo(categoryVO.getCategoryNo());
        categoryConditionService.deleteByCategoryNo(categoryVO.getCategoryNo());
        List<CategoryCoefficentVO> coefficentVOs = categoryVO.getCategoryCoefficentVOs();
        if (CollUtil.isNotEmpty(coefficentVOs)) {
            coefficentVOs.forEach(co->co.setCategoryNo(categoryVO.getCategoryNo()));
            categoryCoefficentService.saveBatch(BeanConv.toBeanList(coefficentVOs, CategoryCoefficent.class));
        }
        List<CategorySafeguardVO> safeguardVOs = categoryVO.getCategorySafeguardVOs();
        if (CollUtil.isNotEmpty(safeguardVOs)) {
            safeguardVOs.forEach(co->co.setCategoryNo(categoryVO.getCategoryNo()));
            categorySafeguardService.saveBatch(BeanConv.toBeanList(safeguardVOs, CategorySafeguard.class));
        }
        List<CategoryConditionVO> conditionVOs = categoryVO.getCategoryConditionVOs();
        if (CollUtil.isNotEmpty(conditionVOs)) {
            conditionVOs.forEach(co->co.setCategoryNo(categoryVO.getCategoryNo()));
            categoryConditionService.saveBatch(BeanConv.toBeanList(conditionVOs, CategoryCondition.class));
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        return null;
    }

    @Override
    public List<CategoryVO> findList(CategoryVO categoryVO) {
        //TODO
        LambdaQueryWrapper<Category> lqw = queryWrapper(categoryVO);
        List<Category> list = this.list(lqw);
        List<CategoryVO> voList = BeanConv.toBeanList(list, CategoryVO.class);
        if(voList.isEmpty()){
            return new ArrayList<>();
        }
        List<Long> nodeFloors = categoryVO.getNodeFloors();
        if (CollUtil.isNotEmpty(nodeFloors)) {
            voList = voList.stream().filter(vo->{
                long level = NoProcessing.processString(vo.getCategoryNo()).length()/3 -1 ;
                return nodeFloors.contains(level);
            }).collect(Collectors.toList());
        }
        buildVoList(voList);
        return voList;
    }



    @Override
    public TreeVO categoryTreeVO(String parentCategoryNo, String categoryType,String[] checkedCategoryNos) {
        //TODO
        String rootNo = StrUtil.isBlank(parentCategoryNo)?SuperConstant.ROOT_PARENT_ID:parentCategoryNo;
        String head = NoProcessing.processString(rootNo);
        List<Category> list = lambdaQuery()
                .likeRight(Category::getCategoryNo, head)
                .eq(StrUtil.isNotBlank(categoryType), Category::getCategoryType, categoryType)
                .list();
        if(CollUtil.isEmpty(list)){
            return TreeVO.builder().build();
        }
        List<TreeItemVO> treeList = list.stream().map(ca -> TreeItemVO.builder()
                .id(ca.getCategoryNo())
                .parentId(ca.getParentCategoryNo())
                .label(ca.getCategoryName())
                .build()).collect(Collectors.toList());
        Map<String, List<TreeItemVO>> treeMap = treeList.stream().collect(Collectors.groupingBy(TreeItemVO::getParentId));
        for (TreeItemVO itemVO : treeList) {
            List<TreeItemVO> voList = treeMap.get(itemVO.getId());
            itemVO.setChildren(voList);
        }
        return TreeVO.builder()
                .items(treeMap.get(rootNo))
                .build();
    }

    @Override
    public String createCategoryNo(String parentCategoryNo) {
        CategoryVO categoryVO = CategoryVO.builder()
            .parentCategoryNo(parentCategoryNo)
            .build();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Category::getParentCategoryNo,parentCategoryNo);
        List<Category> categoryList = list(queryWrapper);
        //无下属节点则创建下属节点
        if (EmptyUtil.isNullOrEmpty(categoryList)){
            return NoProcessing.createNo(parentCategoryNo,false);
        //有下属节点则累加下属节点
        }else {
            Long categoryNo = categoryList.stream()
                .map(category -> { return Long.valueOf(category.getCategoryNo());})
                .max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(categoryNo),true);
        }
    }

    /**
     * 人种榜险种榜分类
      * @param type
     */
    @Override
    public List<CategoryVO> categoryCheckRule(String type) {
        //判断是否是险种榜
        if(InsureConstant.checkIsInsureType(type)){
            List<CategoryVO> res = new ArrayList<>();
            //获取所有的险种榜
            List<String> allCheckRule = InsureConstant.getAllCheckRule();
            allCheckRule.forEach(e->{
                CategoryVO categoryVO = CategoryVO.builder().categoryNo(e).categoryName(InsureConstant.getRuleNameById(e)).build();
                res.add(categoryVO);
            });
            return res;
        }else{
            //说明是人种榜
            List<String> categoryNames = Arrays.asList("成年人", "少儿", "老人");
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Category::getCategoryName,categoryNames);
            queryWrapper.eq(Category::getDataState,SuperConstant.DATA_STATE_0);
            List<CategoryVO> res = BeanConv.toBeanList(list(queryWrapper), CategoryVO.class);
            return res;
        }
    }
}
